<?php

/**
 * Default UserExtraController
 *
 *
 * @package 	laravel
 * @subpackage	app/controllers
 * @version 	1.0.0
 */

class UserExtraController extends BaseController {

	public $data = array();            //传入view的数据
	public $need_redirect = 0;         //是否需要跳转

	/**
	 * 构造函数
	 *
	 */
	public function __construct(){
		session_start();

        $this->data['user_agent'] = $this->getUserAgent();

	}



    //用户个人中心
    public function userCenter(){
		if( empty($_SESSION['user_id']) ){
			$state          = urlencode( Config::get("lib.app_url") );
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return Redirect::to($redirectUrl);
        }else{
			$this->data['user_id'] = $_SESSION['user_id'];
		}

        // if( $this->need_redirect == 1 ){
		// 	$current_uri     = $_SERVER['REQUEST_URI'];
		// 	$current_uri_arr = explode('?' , $current_uri);
		// 	$current_uri     = $current_uri_arr[0];
		// 	$opt_uri     = "";
		// 	$opt_uri_arr = array();
		// 	$input_arr   = Input::all();
		// 	foreach( $input_arr as $key1 => $val1 ){
		// 		if( $key1 != 'token' ){
		// 			$opt_uri_arr[$key1] = $val1;
		// 			if( $opt_uri != "" ){
		// 				$opt_uri .= '&'.$key1.'='.$val1;
		// 			}else{
		// 				$opt_uri .= $key1.'='.$val1;
		// 			}
		// 		}
		// 	}
		// 	if( $opt_uri != "" ){
		// 		$temp = mt_rand(0,100000000);
		// 		$current_uri .= '?'.$opt_uri."&view=".$temp;
		// 	}
		// 	return Redirect::to($current_uri);
		// }

        //未登录直接跳转到首页
        $user_id = $_SESSION['user_id'];
		$this->data['user_id'] = $user_id;
        $user_info = DB::table('user')->where('id','=',$user_id)->get();

        if( count($user_info) == 0 ){
            return Redirect::to('/');
        }
		// if( $user_info[0]->number == '' ){
		// 	$back_uri = Config::get('lib.app_url')."/center";
		// 	$auth_uri = Config::get('lib.campus_uri')."/auth?state=".urlencode($back_uri)."&user_id=".$user_id."&system_cat=library";
		// 	return Redirect::to($auth_uri);
		// }

        $info_arr = array(
            'over_num' => $user_info[0]->over_num ,
            'level' => $user_info[0]->level ,
            'five' => $user_info[0]->five ,
            'count' => $user_info[0]->count ,
            'own' => $user_info[0]->own ,
            'sync_time' => $user_info[0]->sync_time
            );
        $this->data['is_imported'] = 1;
        if( $user_info[0]->sync_time == '0000-00-00 00:00:00' ){
            $this->data['is_imported'] = 0;
        }

        $this->data['info_arr'] = $info_arr;
        return View::make('user_center' , $this->data);
    }


    //用户关注的图书页
    public function userCollection(){

		if( empty($_SESSION['user_id']) ){
			$state          = urlencode( Config::get("lib.app_url") );
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return Redirect::to($redirectUrl);
        }else{
			$this->data['user_id'] = $_SESSION['user_id'];
		}
        $user_id = $_SESSION['user_id'];

        $result = DB::table('user_collection')->where('user_id','=',$user_id)->get();
        $return_arr = array();
        foreach( $result as $key => $val ){
            $temp_no = $val->mac_no;
            $temp_no_length = strlen($temp_no);
            $temp_no_attach = "";
            if( $temp_no_length < 10 ){
                $split = 10 - $temp_no_length;
                for( $i=1 ; $i<=$split ; $i++ ){
                    $temp_no_attach .= '0';
                }
                $temp_no = $temp_no_attach.$temp_no;
            }
            $temp_href = "item.php?marc_no=".$temp_no;
            $return_arr[] = array(
                'mac_no' => $temp_no ,
                'title' => $val->title ,
                'href' => $temp_href ,
                'author' => $val->author ,
                'brief' => $val->brief ,
                'press' => $val->press ,
                'pic' => $val->pic ,
                'index' => $val->index ,
                'add_time' => $val->add_time
            );
        }
        $this->data['result'] = $return_arr;
        $this->data['count'] = count($return_arr);
        return View::make("blike" , $this->data);
    }



    //用户当前借阅
    public function userCurrentRent(){

		if( empty($_SESSION['user_id']) ){
			$state          = urlencode( Config::get("lib.app_url") );
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return Redirect::to($redirectUrl);
        }else{
			$this->data['user_id'] = $_SESSION['user_id'];
		}
        $user_id = $_SESSION['user_id'];

        $result = DB::table('user_rent')->where('user_id','=',$user_id)->get();
		$user_result = DB::table('user')->where('id' , '=' , $user_id)->get();
		if( !empty($user_result) ){
			$this->data['sync_time'] = $user_result[0]->sync_time;
		}

        $this->data['result'] = $result;

        return View::make('bnow' , $this->data);
    }



    //用户借阅历史
    public function userRentHistory(){

		if( empty($_SESSION['user_id']) ){
			$state          = urlencode( Config::get("lib.app_url") );
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return Redirect::to($redirectUrl);
        }else{
			$this->data['user_id'] = $_SESSION['user_id'];
		}
        $user_id = $_SESSION['user_id'];

        $result = DB::table('user_rent_history')->where('user_id','=',$user_id)->get();
		$user_result = DB::table('user')->where('id' , '=' , $user_id)->get();
		if( !empty($user_result) ){
			$this->data['sync_time'] = $user_result[0]->sync_time;
		}

        $this->data['result'] = $result;

        return View::make('bhistory' , $this->data);
    }



    //用户续借 操作 1
    //检查用户图书馆session是否过期
    public function reRentBookCheck(){
        if( !Session::has('user_id') ){
            return Response::json( ['error'=>true , 'errorcode'=>'-1' , 'message'=>'请重新登录'] , 200 );
        }
        $user_id = Session::get('user_id');

		include( app_path()."/libraries/Snoopy.class.php");

        //获取个人证件信息
		$snoopy = new Snoopy;
		$snoopy->host = "202.206.242.99";
		$snoopy->agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
		$snoopy->cookies['PHPSESSID'] = Session::get('pre_session');
		$snoopy->fetch("http://202.206.242.99/reader/redr_info.php");
		$result = $snoopy->results;

		if( $snoopy->timed_out ){
			return Response::json( ['error'=>true , 'message'=>'图书馆身份信息已失效 , 请重新登录'] , 200 );
		}
		if( !stripos($result , "证件信息") ){
			return Response::json( ['error'=>true , 'message'=>'图书馆身份信息已失效 , 请重新登录'] , 200 );
		}else{
            return Response::json( ['error'=>false , 'message'=>'身份信息有效，请获取验证码'] , 200 );
        }
    }


	//获取续借验证码
	public function reRentPic(){

		$user_id = $_SESSION['user_id'];
		$arr = array(
			'method' => 'POST' ,
			'path' => 'rerent/pic' ,
			'query' => array(
				'url' => Input::get('url') ,
				'type' => Input::get('type') ,
				'call_no' => Input::has('call_no')
				)
			);
		$uri = Config::get('lib.ptime_api')."/user/".$user_id."/system_cat/library/api";
		$verify = $this->curl_post( $uri , $arr , "campus" , "" );
		$verify_result = json_decode($verify , true);

		if( isset($verify_result['error']) ){
			if( $verify_result['error'] ){
				if( $verify_result['result'] == 'tokenNull' || $verify_result['result'] == 'tokenTimeOut' ){
					return Response::json(['error'=>true , 'result'=>[] , 'message'=>'请求失败1'] , 200);
				}else{
					return Response::json(['error'=>true , 'result'=>[] , 'message'=>$verify_result['message']] , 200);
				}
			}else{
				return Response::json(['error'=>false , 'result'=>$verify_result['result'] , 'message'=>''] , 200);
			}
		}else{
			return Response::json(['error'=>true , 'result'=>[] , 'message'=>'请求失败2'] , 200);
		}
	}


	//续借
    public function reRentBook(){

		$user_id = $_SESSION['user_id'];
        //检查验证码
        if( !Input::has('vcode') ){
            return Response::json( ['error'=>true , 'message'=>'验证码不能为空'] , 200 );
        }
        $vcode = Input::get('vcode');

        //user_rent表中记录的id
        if( !Input::has('rent_id') ){
            return Response::json( ['error'=>true , 'message'=>'无法续借该图书'] , 200 );
        }
        $rent_id = Input::get('rent_id');

        //查找图书的bar_code和check_code
        $rent_detail = DB::table('user_rent')->where('id','=',$rent_id)->get();
        if( count($rent_detail) == 0 ){
            return Response::json( ['error'=>true , 'message'=>'无法续借该图书'] , 200 );
        }
        $bar_code = $rent_detail[0]->bar_code;
        $check = $rent_detail[0]->check_code;

		$arr = array(
			'method' => 'POST' ,
			'path' => 'rerent' ,
			'query' => array(
				'bar_code' => $bar_code ,
				'check' => $check ,
				'captcha' => $vcode
				)
			);
		$uri = Config::get('lib.ptime_api')."/user/".$user_id."/system_cat/library/api";
		$verify = $this->curl_post( $uri , $arr , "campus" , "" );
		$verify_result = json_decode($verify , true);

		if( isset($verify_result['error']) ){
			if( $verify_result['error'] ){
				if( $verify_result['result'] == 'tokenNull' || $verify_result['result'] == 'tokenTimeOut' ){
					return Response::json(['error'=>true , 'result'=>'tokenNull' , 'message'=>'续借失败1'] , 200);
				}else{
					return Response::json(['error'=>true , 'result'=>[] , 'message'=>$verify_result['message']] , 200);
				}
			}else{
				return Response::json(['error'=>false , 'result'=>[] , 'message'=>'续借成功'] , 200);
			}
		}else{
			return Response::json(['error'=>true , 'result'=>[] , 'message'=>'续借失败2'] , 200);
		}
    }



	//判断用户是否同步过
	public function checkSync(){
		if( !Session::has('user_id') ){
            return Response::json( ['error'=>true , 'errorcode'=>'-1' , 'message'=>'请重新登录'] , 200 );
        }
        $user_id = Session::get('user_id');

		$user_result = DB::table('user')->where('id','=',$user_id)->get();
		if( count($user_result) == 0 ){
			return Response::json( ['error'=>true , 'errorcode'=>'-1' , 'message'=>'无此用户，请重新登录'] , 200 );
		}

		if( $user_result[0]->over_num == "" && $user_result[0]->rss == "" ){
			return Response::json( ['error'=>true , 'message'=>'您还未同步过数据，请点击同步'] , 200 );
		}else{
			return Response::json( ['error'=>false , 'message'=>'已同步过'] , 200 );
		}
	}


	//执行预约操作
	public function doOrder(){

	}



    //获取用户user-agent
    public function getUserAgent(){
        if( strpos($_SERVER['HTTP_USER_AGENT'], 'PTime.IOSWeb') !== false):
            $userAgent = "ptimeios";
        elseif( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false):
            $userAgent = "wechat";
        elseif( strpos($_SERVER['HTTP_USER_AGENT'], 'PTime.AndroidWeb') !== false):
            $userAgent = "ptimeandroid";
        elseif( strpos($_SERVER['HTTP_USER_AGENT'], 'MQQBrowser')!== false):
            $userAgent = "mqq";
        else:
            $userAgent = "other";
        endif;
        return $userAgent;
    }

}
